package my.action.author;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.*;

import my.controller.*;
import my.db.DAO.ArticleDAO;
import my.db.DAO.AuthenticationDAO;
import my.db.DAO.AuthorDAO;
import my.db.DTO.AuthenticationDTO;
import my.db.DTO.AuthorDTO;
public class AuthorAddAction implements  Action{
	public Date getMachineTime()// Getting date from time marchine
	{
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
		Calendar cal = Calendar.getInstance();
		return cal.getTime();
	}
	 public ActionForward execute(HttpServletRequest request,HttpServletResponse response) throws Exception{
			//fields
		 	AuthorDAO authorDAO=new AuthorDAO();
			AuthorDTO authorDTO=null;
			AuthenticationDTO autDTO=null;
			AuthenticationDAO autDAO=new AuthenticationDAO();
		   	ActionForward forward=new ActionForward();
		   	boolean result=true;
	   		try{   	   		
	   			//Author information 
	   			String fname=request.getParameter("fname"); // return fname
	   			String lname=request.getParameter("lname"); // return lname
	   			String fullname =lname +"  "+fname; // return fullname , fname + lname	
	   			int gender=Integer.parseInt(request.getParameter("authorgender"));//return gender 1 or 0
	   			String email=request.getParameter("email");// return email address
	   			String phone=request.getParameter("authorphone");// return phone
	   			int status=1; // return status
	   			
	   			// Account user information
	   			String user=request.getParameter("username");// reutrn username 
	   			String pwd=request.getParameter("userpwd"); // return user password
	   			autDTO=autDAO.getAccountUser(user); 
	   			authorDTO=authorDAO.getUserMail(email);
	   			
	   			// check condition
	   			if(autDTO !=null){// compare if username is existed return false 
	   				forward.setPath("./register.jsp?error=Account name is already exist");
	   				result=false;
	   			}
	   			
	   			if(authorDTO !=null){//compare if email is existed return false 
	   				forward.setPath("./register.jsp?error=Email is already exist");
	   				result=false;
	   				
	   			}if(autDTO ==null && authorDTO ==null)// if username and email aren't existed 
	   			{
	   				result=authorDAO.addNewAuthor(fullname,gender,email,phone,status,getMachineTime());	 
	   				if(result==true){
	   					autDTO=new AuthenticationDTO();
			   			autDTO.setAccountName(user);
			   			autDTO.setAccountPassword(pwd);
			   			autDTO.setPosition("author");
			   			System.out.println(autDTO.toString());
			   			result=autDAO.addAccount(autDTO);// add new author and account 
			   			forward.setRedirect(false);	   		 
			   			forward.setPath("./register.jsp?success=successfully added");
	   				}   				
	   			}
	   				
	  		}catch(Exception ex){
	  			//System.out.println(ex);
	   		}
	  		return forward;
		}  	
}